import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./config";
import store from "@/store";
// hack router push callback
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};

Vue.use(VueRouter);

const router = new VueRouter({
  // mode: 'history', // 如果你是 history模式 需要配置vue.config.js publicPath
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 滚动行为
    if (savedPosition) {
      return savedPosition;
    }
    return { x: 0, y: 0 };
  }
});

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token');
  // console.log(token)
  // 全局配置请求
  // store.dispatch('config')
  
  if (token) {
    store.commit("SET_ACCESS_TOKEN", token);
    if (to.matched.length === 0) {
      // 匹配不到相对应的路由时，跳转到首页
      const toPath = to.name ? { name: to.name } : "/";
      next(toPath);
      return;
    }
    next();
  } else {
    console.log('没有token')
    console.log(to)
    let arr = ['/agreement', '/privacy']
    if (to.path !== '/login' && !arr.includes(to.path)) {
      next('/login');
    }
    next();
  }
  // 设置标题
  if (to.meta && to.meta.title) {
    document.title = to.meta.title;
  }
});

export default router;
